package com.caiyi.financial.nirvana.sms.scheduled;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.service.SmsUserService;
import com.caiyi.financial.nirvana.sms.util.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@Component
public class RemoveQueryReportTask {

    private static final Logger logger = LoggerFactory.getLogger(RemoveQueryReportTask.class);

    @Autowired
    private SmsUserService userService;

    /**
     * 每小时清除redis中存储短信状态报告过期数据
     */
    @Scheduled(cron = "0 0 */1 * * ?")
    public void removeQueryReportKey() {
        logger.info("RemoveQueryReportTask run removeQueryReportKey start......");
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            List<String> list = userService.selectAccountList();
            if (null != list && list.size() > 0) {
                for (String account : list) {
                    String key = String.format(JedisKey.SMS_QUEUE_REPORT_LIST_ACCOUNT, account);
                    long startSize = JedisService.llen(key);
                    //获取到短信状态报告，若接受时间大于1天，则释放
                    for (int i = 0; i < startSize; i++) {
                        String jsonStr = JedisService.lpop(key);
                        Map map = (Map) JSON.parse(jsonStr);
                        long endTime = System.currentTimeMillis();
                        long startTime = map.get("receiveTime") == null ? 0l : simple.parse(map.get("receiveTime") + "").getTime();
                        if (endTime - startTime < Constant.DAY_OF_SECOND * 1000) {
                            JedisService.lpush(key, jsonStr);
                            break;
                        }
                    }
                    long endSize = JedisService.llen(key);
                    logger.info("RemoveQueryReportTask account : {}, startSize : {}, endSize {} ", account, startSize, endSize);
                }
            }
        } catch (Exception e) {
            logger.error("RemoveQueryReportTask run removeQueryReportKey error :{}", e);
        }
    }

}
